<?php
/**
 * Created by PhpStorm.
 * User: linhongzhao
 * Date: 18-5-13
 * Time: 上午12:20
 */

namespace EFrame;
use EFrame\Cache\Pool\ArrayCachePool;
use Psr\Cache\CacheItemPoolInterface;

/**
 * Class Cache
 * Cache统一访问入口
 * @package EFrame
 */
class Cache
{
    protected static $default_pool_type = 'array';

    protected static $pool_map = [
        'array' => ArrayCachePool::class,
    ];
    protected static $pool_types = ['array'];

    /**
     * @var CacheItemPoolInterface[]
     */
    protected static $instances = [];

    /**
     * @var CacheItemPoolInterface
     */
    protected $pool;

    /**
     * Cache constructor.
     * @param CacheItemPoolInterface $pool
     */
    public function __construct(CacheItemPoolInterface $pool)
    {
        $this->pool = $pool;
    }

    /**
     * 获取一个缓存实例
     * 为了提高执行效率，建议提供options['type']和name
     * @param array $options
     * @param string $name
     * @return CacheItemPoolInterface
     */
    public static function getInstance($options, $name = '') {
        if (empty($name)) {
            $name = md5(serialize($options));
        }
        if (isset(self::$instances[$name])) {
            return self::$instances[$name];
        }

        if (!isset($options['type'])) {
            $options['type'] = self::$default_pool_type;
        }

        self::$instances[$name] = new self::$pool_map[$options['type']]($options);

        return self::$instances[$name];
    }

    /**
     * 获取所有支持的cache类型
     * @param bool $is_print
     * @return string[]
     */
    public static function getCacheTypes($is_print = true) {
        $types = array_keys(self::$pool_types);
        if ($is_print) {
            print_r($types);
        }
        return $types;
    }
}